import os.path
import time

import requests
from PyQt5.QtGui import QIcon, QBrush, QPixmap, QPalette
from PyQt5.QtWidgets import QWidget

from ui.Login_and_signup_window import Login_and_signup_window

import global_config
from window.My_forget_password_window import My_forget_password_window
from window.My_logined_in_window import My_logined_in_window
from window.My_pop_up_to_input import My_pop_up_to_input
from window.My_pop_up_warning import My_pop_up_warning


class My_login_and_signup_window(QWidget, Login_and_signup_window):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        base_path = os.path.dirname(__file__)
        base_path = base_path.replace('\\window', '')

        icon_path = os.path.join(base_path, 'icon')
        # 设置界面标题、图标等
        self.setWindowTitle('登录和注册')
        icon = QIcon(os.path.join(icon_path, 'python.png'))
        self.setWindowIcon(icon)

        # 设置背景图片
        back_path = os.path.join(base_path, 'background')
        back_path = os.path.join(back_path, 'background.jpg')
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QPixmap(back_path)))
        self.setPalette(palette)

        self.random_dialog.setText('')
        self.display_random_dialog()

        # 在特定条件下弹出的警告界面
        self.pop_up_warning = My_pop_up_warning()

        # 在特定条件下弹出的登录成功后的页面
        self.logined_in_window = My_logined_in_window()

        # 忘记密码的页面
        self.forget_password_window = My_forget_password_window()
        self.pop_up_to_input = My_pop_up_to_input()
        self.forget_password_window.setWindowIcon(icon)
        self.pop_up_to_input.setWindowIcon(icon)

        # 将登录界面显示为首页
        self.tabWidget.setCurrentIndex(0)

        # 设置登录界面的警告初始不可见
        self.input_username_in_login.setPlaceholderText('请输入用户名：')
        self.input_password_in_login.setPlaceholderText('请输入密码：')
        self.input_username_in_signup.setPlaceholderText('请输入用户名：')
        self.input_password_in_signup.setPlaceholderText('请输入密码：')
        self.input_password_to_confirm_in_signup.setPlaceholderText('请再次输入密码：')

        self.input_username_is_none_in_login.setText('')
        self.input_password_is_none_in_login.setText('')
        self.input_username_wrong_in_signup.setText('')
        self.input_password_wrong_in_signup.setText('')
        self.input_password_to_confirm_wrong_in_signup.setText('')

        # username_in_login 控件监听键盘输入事件
        self.input_username_in_login.textChanged.connect(self.update_input_username_is_none_in_login)
        self.input_password_in_login.textChanged.connect(self.update_input_password_is_none_in_login)
        self.input_username_in_signup.textChanged.connect(self.update_input_username_wrong_in_signup)
        self.input_password_in_signup.textChanged.connect(self.update_input_password_wrong_in_signup)
        self.input_password_to_confirm_in_signup.textChanged.connect(
            self.update_input_password_to_confirm_wrong_in_signup)

        # 登录与注册界面切换
        self.signup_button_in_login.clicked.connect(self.switch_to_signup_window)
        self.return_to_login_button_in_signup.clicked.connect(self.switch_to_login_window)

        # 登录确认按钮
        self.confirm_button_in_login.clicked.connect(self.attempt_to_login)

        # 注册确认按钮
        self.confirm_button_in_signup.clicked.connect(self.attempt_to_signup)

        # 忘记密码按钮
        self.forget_password_button_in_login.clicked.connect(self.pop_up_to_input_window)

        # 当登录进去的界面关闭后，再显示出这个界面
        self.logined_in_window.close_signal.connect(self.show)

    def pop_up_to_input_window(self):
        self.pop_up_to_input.show()

    def pop_up_forget_password_window(self):
        self.forget_password_window.show()

    def update_input_username_is_none_in_login(self):
        if self.input_username_in_login.text() == '':
            self.input_username_is_none_in_login.setText('用户名不能为空')
        else:
            self.input_username_is_none_in_login.setText('')

    def update_input_password_is_none_in_login(self):
        if self.input_password_in_login.text() == '':
            self.input_password_is_none_in_login.setText('密码不能为空')
        else:
            self.input_password_is_none_in_login.setText('')

    def update_input_username_wrong_in_signup(self):
        if self.input_username_in_signup.text() == '':
            self.input_username_wrong_in_signup.setText('用户名不能为空')
        else:
            self.input_username_wrong_in_signup.setText('')

    def update_input_password_wrong_in_signup(self):
        if self.input_password_in_signup.text() == '':
            self.input_password_wrong_in_signup.setText('密码不能为空')
        elif self.check_password(self.input_password_in_signup.text()):
            self.input_password_wrong_in_signup.setText('密码应包含大小写字母和数字')
        else:
            self.input_password_wrong_in_signup.setText('')

    def update_input_password_to_confirm_wrong_in_signup(self):
        if self.input_password_to_confirm_in_signup.text() == '':
            self.input_password_to_confirm_wrong_in_signup.setText('密码不能为空')
        elif self.input_password_to_confirm_in_signup.text() != self.input_password_in_signup.text():
            self.input_password_to_confirm_wrong_in_signup.setText('两次密码输入不一致')
        else:
            self.input_password_to_confirm_wrong_in_signup.setText('')

    def check_password(self, password):
        result1 = False
        result2 = False
        result3 = False
        for i in password:
            if '0' <= i <= '9':
                result1 = True
            elif 'a' <= i <= 'z':
                result2 = True
            elif 'A' <= i <= 'Z':
                result3 = True
        return not (result1 and result2 and result3)

    def switch_to_signup_window(self):
        # 将注册界面显示为首页
        self.tabWidget.setCurrentIndex(1)
        # 将缓存信息去掉
        self.input_username_in_login.setText('')
        self.input_password_in_login.setText('')
        self.input_username_is_none_in_login.setText('')
        self.input_password_is_none_in_login.setText('')

    def switch_to_login_window(self):
        # 将登录界面显示为首页
        self.tabWidget.setCurrentIndex(0)
        # 将缓存信息去掉
        self.input_username_in_signup.setText('')
        self.input_password_in_signup.setText('')
        self.input_password_to_confirm_in_signup.setText('')
        self.input_username_wrong_in_signup.setText('')
        self.input_password_wrong_in_signup.setText('')
        self.input_password_to_confirm_wrong_in_signup.setText('')

    def attempt_to_login(self):
        # 定义错误符
        error = False

        if self.input_username_in_login.text() == '':
            error = True
            self.input_username_is_none_in_login.setText('用户名不能为空')

        if self.input_password_in_login.text() == '':
            error = True
            self.input_password_is_none_in_login.setText('密码不能为空')

        # 向后端发送信息
        if not error:
            url = 'http://' + global_config.localhost + ':8000/login/'
            params = {
                'username': self.input_username_in_login.text(),
                'password': self.input_password_in_login.text()
            }

            result = requests.get(url, params=params).json()

            if result['result'] == 'success':
                username = self.input_username_in_login.text()
                password = self.input_password_in_login.text()
                login_time = time.strftime('%Y-%m-%d \n%H:%M:%S', time.localtime())
                # 设置登录进去后的页面的用户名和密码以便展示
                self.logined_in_window.set_username(username)
                self.logined_in_window.set_password(password)
                self.logined_in_window.set_login_time(login_time)
                # 加载历史信息
                self.logined_in_window.load_history_page()
                self.logined_in_window.set_username(username)

                # 当登录进去之后把登录和注册界面关闭
                self.close()
                self.logined_in_window.show()
                self.input_password_in_login.setText('')
                self.input_password_is_none_in_login.setText('')
            elif result['result'] == 'logined':
                self.pop_up_warning.warning_info_label.setText('登录出错了')
                self.pop_up_warning.warning_info_text.setText('该账号已在某地登录')
                self.pop_up_warning.show()
            elif result['result'] == 'wrong':
                self.pop_up_warning.warning_info_label.setText('登录出错了')
                self.pop_up_warning.warning_info_text.setText('用户名或密码不正确')
                self.pop_up_warning.show()

    def attempt_to_signup(self):
        # 定义是否有地方为空
        is_empty = False
        error = False

        if self.input_username_in_signup.text() == '':
            is_empty = True
            error = True
            self.input_username_wrong_in_signup.setText('用户名不能为空')

        if self.input_password_in_signup.text() == '':
            is_empty = True
            error = True
            self.input_password_wrong_in_signup.setText('密码不能为空')

        if self.input_password_to_confirm_in_signup.text() == '':
            is_empty = True
            error = True
            self.input_password_to_confirm_wrong_in_signup.setText('密码不能为空')

        if self.check_password(self.input_password_in_signup.text()):
            error = True
            self.input_password_wrong_in_signup.setText('密码应包含大小写字母和数字')

        # 如果三个文本框均不为空
        if not is_empty and self.input_password_in_signup.text() != self.input_password_to_confirm_in_signup.text():
            error = True
            self.input_password_wrong_in_signup.setText('两次密码输入不一致')
            self.input_password_to_confirm_wrong_in_signup.setText('两次密码输入不一致')

        if not error:
            url = 'http://' + global_config.localhost + ':8000/register/'
            params = {
                'username': self.input_username_in_signup.text(),
                'password': self.input_password_in_signup.text(),
                'password_confirm': self.input_password_to_confirm_in_signup.text()
            }

            result = requests.get(url, params=params).json()
            if result['result'] == 'success':
                # 注册成功，自动切换到登录界面，并自动填上注册的用户名和密码，提高用户友好度
                username = self.input_username_in_signup.text()
                password = self.input_password_in_signup.text()
                self.input_username_in_login.setText(username)
                self.input_password_in_login.setText(password)
                self.switch_to_login_window()
            elif result['result'] == 'exist':
                self.pop_up_warning.warning_info_label.setText('注册出错了')
                self.pop_up_warning.warning_info_text.setText('该用户名已被注册')
                self.pop_up_warning.show()
            elif result['result'] == 'mismatch':
                self.pop_up_warning.warning_info_label.setText('注册出错了')
                self.pop_up_warning.warning_info_text.setText('两次密码输入不一致')
                self.pop_up_warning.show()
            elif result['result'] == 'empty-u(username)':
                self.pop_up_warning.warning_info_label.setText('注册出错了')
                self.pop_up_warning.warning_info_text.setText('用户名不能为空')
                self.pop_up_warning.show()
            elif result['result'] == 'empty-p(password)':
                self.pop_up_warning.warning_info_label.setText('注册出错了')
                self.pop_up_warning.warning_info_text.setText('密码不能为空')
                self.pop_up_warning.show()
            elif result['result'] == 'empty-c(password_confirm)':
                self.pop_up_warning.warning_info_label.setText('注册出错了')
                self.pop_up_warning.warning_info_text.setText('密码不能为空')
                self.pop_up_warning.show()

    def display_random_dialog(self):
        self.random_dialog.setText('v2.0.0')

    def closeEvent(self, event):
        self.pop_up_warning.close()
        self.pop_up_to_input.close()
